package com.tally.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tally.gateway.enums.RequestPathIgnoreEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: sy
 * @Date: 2020/12/21 13:13
 * @Description:
 */
@Component
public class LoginGatewayFilter implements GatewayFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(LoginGatewayFilter.class);
    private static final String LOGIN_SUFFIX = "-login";
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${key.expire-time.login}")
    private Long loginExpireTime;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        // 请求地址中包含在RequestPathEnum中的（可自行添加），不需要登录拦截
        for(RequestPathIgnoreEnum requestPathIgnore : RequestPathIgnoreEnum.values()){
            if(path.contains(requestPathIgnore.getPath())){
                logger.info("不需要控台登录验证：{}",path);
                return chain.filter(exchange);
            }
        }

        // 获取header里的token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        logger.info("登录拦截开始，token：{}",token);
        if(StringUtils.isEmpty(token)){
            logger.info("token为空，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        Object obj = redisTemplate.opsForValue().get(token + LOGIN_SUFFIX);
        if(obj == null){
            logger.warn("token无效，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        logger.info("已登录：{}",obj);

        JSONObject loginUserDTO = JSON.parseObject(String.valueOf(obj));
        // 刷新token时间
        redisTemplate.opsForValue().set(token + LOGIN_SUFFIX, JSON.toJSONString(loginUserDTO),loginExpireTime, TimeUnit.SECONDS);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
